package com.future.allUtils.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;


public class JwtUtil {

    public static final Long JWT_TTL = 60 * 60 * 1000L;
    // 使用预生成的强密钥
    public static final String JWT_KEY = "d7Ef9gH2jK4mNp3RsTuVxYzA1bBcD5eF6hJ8kL0oP9qQ";

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String createJWT(String subject, Long ttlMillis) {
        return getJwtBuilder(subject, ttlMillis, getUUID()).compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis == null) ttlMillis = JWT_TTL;

        return Jwts.builder()
                .setId(uuid)
                .setSubject(subject)
                .setIssuer("huayue")
                .setIssuedAt(now)
                .signWith(secretKey)
                .setExpiration(new Date(nowMillis + ttlMillis));
    }

    public static SecretKey generalKey() {
        // 使用标准Base64解码（不是URL解码！）
        byte[] decodedKey = Base64.getDecoder().decode(JWT_KEY);

        if (decodedKey.length < 32) {
            throw new IllegalArgumentException(
                    "密钥长度不足! 需要 256 位 (32 字节)，实际为 " +
                            (decodedKey.length * 8) + " 位 (" + decodedKey.length + " 字节)");
        }

        return new SecretKeySpec(decodedKey, "HmacSHA256");
    }

    public static Claims parseJWT(String jwt) {
        return Jwts.parserBuilder()
                .setSigningKey(generalKey())
                .build()
                .parseClaimsJws(jwt)
                .getBody();
    }

//    public static void main(String[] args) {
////        // 1. 生成新密钥（只运行一次）
////        SecureRandom secureRandom = new SecureRandom();
////        byte[] key = new byte[32]; // 256位
////        secureRandom.nextBytes(key);
////
////        // 使用URL安全的Base64编码（无填充）
////        String base64Key = Base64.getUrlEncoder().withoutPadding().encodeToString(key);
////        System.out.println("新密钥: " + base64Key);
////        System.out.println("密钥长度: " + base64Key.length() + " 字符");
////
////        // 测试解码
////        byte[] decoded = Base64.getUrlDecoder().decode(base64Key);
////        System.out.println("解码后字节长度: " + decoded.length + " 字节");
//
//        // 2. 测试JWT功能
//        String subject = "test-user";
//        String jwt = createJWT(subject, 3600000L);
//        System.out.println("生成的JWT: " + jwt);
//
//        Claims claims = parseJWT(jwt);
//        System.out.println("解析的Claims: " + claims);
//    }
}